import { app, shell, BrowserWindow, ipcMain, Tray, Menu, dialog, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { handleUserLogOut } from '../renderer/src/utils/webSocketUtil'
import { ResponseP2PCall } from '../renderer/src/utils/P2PCall'

let mainWindow: BrowserWindow

function createWindow(): void {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 480,
    height: 600,
    resizable: false,
    frame: false,
    icon: icon,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // 允许跨域
      disableBlinkFeatures: 'OutOfBlinkCors'
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: '/'
    })
  }
}

let communicationWindow: BrowserWindow | null

function createCommunicationWindow(datas: any[]) {
  communicationWindow = new BrowserWindow({
    width: 800,
    height: 400,
    resizable: false,
    frame: false,
    parent: mainWindow,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // 允许跨域
      disableBlinkFeatures: 'OutOfBlinkCors'
    }
  })

  communicationWindow.on('ready-to-show', () => {
    if (communicationWindow) {
      communicationWindow.show()
    }

    ipcMain.on('initVuex', () => {
      if (communicationWindow) {
        communicationWindow.webContents.send('initVuex', [datas[0], datas[1]])
      }
    })

    ipcMain.on('close-communication-window', (_, args) => {
      if (mainWindow) {
        mainWindow.webContents.send('call-p2p-remote-disconnect', args)
      }

      if (communicationWindow) {
        communicationWindow.destroy()
        communicationWindow = null
      }
    })

    ipcMain.on('apply-p2p-call', (_, args) => {
      if (mainWindow) {
        mainWindow.webContents.send('apply-p2p-call', args)
      }
    })

    ipcMain.on('notify-p2p-frame-built', (_, args) => {
      if (mainWindow) {
        mainWindow.webContents.send('notify-p2p-frame-built', args)
      }
    })

    ipcMain.on('send-p2p-ice', (_, args) => {
      if (mainWindow) {
        mainWindow.webContents.send('send-p2p-ice', args)
      }
    })

    ipcMain.on('send-p2p-offer', (_, args) => {
      if (mainWindow) {
        mainWindow.webContents.send('send-p2p-offer', args)
      }
    })

    ipcMain.on('send-p2p-answer', (_, args) => {
      if (mainWindow) {
        mainWindow.webContents.send('send-p2p-answer', args)
      }
    })
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    communicationWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#/p2pCall')
  } else {
    communicationWindow.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: '/p2pCall'
    })
  }
}

let communicateNotificationWin: BrowserWindow | null

const createCommunicateNotificationWin = (datas: any[]) => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize

  communicateNotificationWin = new BrowserWindow({
    width: 330,
    height: 100,
    x: width - 330,
    y: height - 100,
    resizable: false,
    frame: false,
    parent: mainWindow,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // 允许跨域
      disableBlinkFeatures: 'OutOfBlinkCors'
    }
  })

  communicateNotificationWin.on('ready-to-show', () => {
    if (communicateNotificationWin) {
      communicateNotificationWin.show()
    }

    ipcMain.on('initVuex', () => {
      if (communicateNotificationWin) {
        communicateNotificationWin.webContents.send('initVuex', [datas[1], datas[2]])
      }
    })

    ipcMain.on('response-call', (_, args) => {
      if (communicateNotificationWin) {
        communicateNotificationWin.destroy()
        communicateNotificationWin = null
        if (mainWindow) {
          mainWindow.webContents.send('response-p2p-call', args[0])
          mainWindow.webContents.send('flush-all-notification-data')
        }

        // 如果同意接听
        if (!communicationWindow && args[0].respStatus) {
          createCommunicationWindow([args[1], args[2]])
        }
      }
    })
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    communicateNotificationWin.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#/callNotification')
  } else {
    communicateNotificationWin.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: '/callNotification'
    })
  }
}

// 用户个人信息窗口
let userProfileWin: BrowserWindow | null = null

const createUserProfileWindow = (datas: any[]) => {
  userProfileWin = new BrowserWindow({
    width: 600,
    height: 500,
    resizable: false,
    frame: false,
    parent: mainWindow,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // 允许跨域
      disableBlinkFeatures: 'OutOfBlinkCors'
    }
  })

  userProfileWin.on('ready-to-show', () => {
    if (userProfileWin) {
      userProfileWin.show()
    }

    ipcMain.on('initVuex', () => {
      if (userProfileWin) {
        userProfileWin.webContents.send('initVuex', [datas])
      }
    })

    ipcMain.on('update-user-profile', () => {
      if (mainWindow) {
        mainWindow.webContents.send('update-user-profile')
      }
    })

    ipcMain.on('close-user-profile', () => {
      if (userProfileWin) {
        userProfileWin.destroy()
        userProfileWin = null
      }
    })
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    userProfileWin.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#/userProfile')
  } else {
    userProfileWin.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: '/userProfile'
    })
  }
}

const showAlert = (title: string, message: string) => {
  dialog.showMessageBox({
    type: 'info',
    buttons: ['确定'],
    title: title,
    defaultId: 0,
    message: message
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  ipcMain.on('close-window', () => {
    mainWindow?.hide()
  })

  ipcMain.on('minimize-window', () => {
    mainWindow?.minimize()
  })

  ipcMain.on('change-window-size', (_, args) => {
    const [width, height] = args
    mainWindow?.setContentSize(width, height)
    mainWindow?.center()
  })

  ipcMain.on('refuse-p2p-call', (_, args) => {
    mainWindow?.webContents.send('refuse-p2p-call', args)
  })

  ipcMain.on('show-user-profile', (_, args) => {
    if (!userProfileWin) {
      createUserProfileWindow(args)
    }
  })

  ipcMain.on('create-communication-window', (_, args) => {
    if (!communicationWindow) {
      createCommunicationWindow(args)
    } else {
      showAlert('打开通话窗口失败', '请关闭当前通话窗口!')
    }
  })

  ipcMain.on('create-communication-notify-window', (_, args) => {
    // 如果没有通知也没通话就创建
    if (!communicateNotificationWin && !communicationWindow) {
      createCommunicateNotificationWin(args)
    }

    // 如果正在通话
    if (communicationWindow) {
      const resp: ResponseP2PCall = args[0]
      resp.respStatus = false
      resp.reason = '对方正在通话中'
      if (mainWindow) {
        mainWindow.webContents.send('response-p2p-call', resp)
      }
    }
  })

  ipcMain.on('clear-chat-input-content', () => {
    if (mainWindow) {
      mainWindow.webContents.send('clear-chat-input-content')
    }
  })

  ipcMain.on('flush-all-p2p-data', () => {
    if (mainWindow) {
      mainWindow.webContents.send('flush-all-p2p-data')
    }
  })

  ipcMain.on('flush-all-notification-data', () => {
    if (mainWindow) {
      mainWindow.webContents.send('flush-all-notification-data')
    }
  })

  ipcMain.on('handle-delete-friend-success', () => {
    if (mainWindow) {
      mainWindow.webContents.send('handle-delete-friend-success')
    }
  })

  ipcMain.on('load-new-msg-audio', () => {
    if (mainWindow) {
      mainWindow.webContents.send('load-new-msg-audio')
    }
  })

  // 通话事件
  ipcMain.on('handle-p2p-call-response', (_, args) => {
    if (communicationWindow) {
      communicationWindow.webContents.send('handle-p2p-call-response', args)
    }
  })

  ipcMain.on('receive-p2p-frame-built', () => {
    if (communicationWindow) {
      communicationWindow.webContents.send('receive-p2p-frame-built')
    }
  })

  ipcMain.on('receive-p2p-call-ice', (_, args) => {
    if (communicationWindow) {
      communicationWindow.webContents.send('receive-p2p-call-ice', args)
    }
  })

  ipcMain.on('receive-p2p-call-offer', (_, args) => {
    if (communicationWindow) {
      communicationWindow.webContents.send('receive-p2p-call-offer', args)
    }
  })

  ipcMain.on('receive-p2p-call-answer', (_, args) => {
    if (communicationWindow) {
      communicationWindow.webContents.send('receive-p2p-call-answer', args)
    }
  })

  ipcMain.on('call-local-p2p-disconnect', () => {
    if (communicationWindow) {
      communicationWindow.webContents.send('call-local-p2p-disconnect')
    }
  })

  ipcMain.on('handle-disconnect-websocket', () => {
    if (mainWindow) {
      if (communicationWindow) {
        communicationWindow.webContents.send('call-local-p2p-disconnect')
      }

      if (communicateNotificationWin) {
        communicateNotificationWin.destroy()
        communicateNotificationWin = null

        if (mainWindow) {
          mainWindow.webContents.send('flush-all-notification-data')
        }
      }

      if (userProfileWin) {
        userProfileWin.destroy()
        userProfileWin = null
      }

      mainWindow.setContentSize(480, 600)
      mainWindow.center()
    }
  })

  const tray = new Tray(icon)

  const contextMenu = Menu.buildFromTemplate([
    {
      label: '退出应用',
      click: function () {
        handleUserLogOut()

        if (communicationWindow) {
          communicationWindow.webContents.send('call-local-p2p-disconnect')
        }

        if (communicateNotificationWin) {
          communicateNotificationWin.destroy()
          communicateNotificationWin = null

          if (mainWindow) {
            mainWindow.webContents.send('flush-all-notification-data')
          }
        }

        if (userProfileWin) {
          userProfileWin.destroy()
          userProfileWin = null
        }

        mainWindow?.destroy()
        app.quit()
      }
    }
  ])

  tray.setIgnoreDoubleClickEvents(true)
  tray.setToolTip('ChatChat')
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    mainWindow?.show()
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
